﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace WebAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class JwtTestController : ControllerBase
    {
        private readonly ILogger<JwtTestController> _logger;

        /// <summary>
        /// 构造注入Log服务
        /// </summary>
        /// <param name="logger"></param>
        public JwtTestController(ILogger<JwtTestController> logger)
        {
            _logger = logger;
        }
        /// <summary>
        ///生成Token方法
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private string BuildToken(string userId)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes("Security:Tokens:Key");// 生成二进制字节数组
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Issuer = "Security:Tokens:Issuer",//发布者
                Audience = "Security:Tokens:Audience",//接受者
                Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userId) }),//Token的身份证，类似一个人可以有身份证，户口本
                Expires = DateTime.UtcNow.AddDays(7), //过期时间
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256) // 用于签发token的秘钥算法
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

        /// <summary>
        /// 第一个Action，根据userName创建Token
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        [HttpGet("GetToken")]
        public IActionResult GetToken(string userName)
        {
            return Ok(new { Token = BuildToken(userName) });//创建一个admin用户的Token
        }


        /// <summary>
        /// 第二个Action，测试Jwt验证
        /// </summary>
        /// <returns></returns>
        [HttpGet("Test")]
        [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] //通过jwt验证
        //[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme + "," + CookieAuthenticationDefaults.AuthenticationScheme)]  通过jwt验证和cookie来验证
        public IActionResult Test()
        {
            return Ok(new { Content = "通过Token验证访问到接口！" });
        }
    }
}
